// pages/api/users.ts
import { NextApiRequest, NextApiResponse } from 'next';
import clientPromise from '../../lib/mongodb';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const client = await clientPromise;
  const db = client.db("mydb");

  switch (req.method) {
    case 'GET':
      const users = await db.collection('users').find({}).limit(10).toArray();
      res.json(users);
      break;

    case 'POST':
      try {
        const newUser = JSON.parse(req.body);
        const result = await db.collection('users').insertOne(newUser);
        res.status(201).json(result.ops[0]);
      } catch (e) {
        res.status(500).json({ error: '创建用户失败' });
      }
      break;

    default:
      res.setHeader('Allow', ['GET', 'POST']);
      res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}